package com.zx._03_并发.chapter_08_threadLocal;

import com.zx.common.util.ThreadUtil;
import javax.servlet.annotation.WebServlet;
import lombok.extern.slf4j.Slf4j;

// https://blog.xiaohansong.com/ThreadLocal-leak-analyze.html
@WebServlet(value = "/qax")
@Slf4j
public class 内存泄露演示 {

    private static final ThreadLocal<MyCounter> myThreadLocal = new ThreadLocal<>() {
        @Override
        protected MyCounter initialValue() {
            return super.initialValue();
        }
    };

    public static void main(final String[] args) {
        final int threadLen = 100;
        for (int i = 0; i < threadLen; i++) {
            Thread thread = new Thread(() -> {
                内存泄露演示.doGet();
            });
            thread.start();
            ThreadUtil.sleepMill(10);
            thread = null;
            System.gc();
        }
    }

    protected static void doGet() {
        MyCounter counter = myThreadLocal.get();
        if (counter == null) {
            counter = new MyCounter();
            myThreadLocal.set(counter);
        }
        log.info("counter={}", counter.getCount());
        counter.increment();
    }

    private static class MyCounter {

        private int count = 8888;

        public void increment() {
            this.count++;
        }

        public int getCount() {
            return this.count;
        }
    }
}
